/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 manticorecao@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */


package com.ksvip.next.components.core;

import org.apache.commons.lang3.time.StopWatch;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 计时器Context
 */
public class StopWatchContext {

    private static final ThreadLocal<Map<String, StopWatch>> WATCH_CTX = new ThreadLocal<Map<String, StopWatch>>() {
        @Override
        protected Map<String, StopWatch> initialValue() {
            return new ConcurrentHashMap<>();
        }
    };

    /**
     * 初始化指定Key的StopWatch
     * @param key
     */
    public static void initWatch(String key){
        if(!WATCH_CTX.get().containsKey(key)) {
            WATCH_CTX.get().put(key, new StopWatch());
        }
    }

    /**
     * 开始计时
     * @param key
     */
    public static void start(String key){ WATCH_CTX.get().get(key).start(); }

    /**
     * 停止计时
     * @param key
     */
    public static void stop(String key){
        WATCH_CTX.get().get(key).stop();
    }

    /**
     * 获取计时时间
     * @param key
     * @return
     */
    public static long getTime(String key){
        return WATCH_CTX.get().get(key).getTime();
    }

    /**
     * 计时器是否已开始计时
     * @param key
     * @return
     */
    public static boolean isStarted(String key){
        return WATCH_CTX.get().get(key).isStarted();
    }

    /**
     * 重置StopWatch(getTime以后需重置以备复用)
     * @param key
     */
    public static void reset(String key){
        WATCH_CTX.get().get(key).reset();
    }

}
